package com.qf.fmw.dao.impl;

import com.qf.fmw.dao.OrderDao;
import com.qf.fmw.entity.bo.OrderBo;
import com.qf.fmw.utils.DBManager;

import java.util.ArrayList;
import java.util.List;

public class OrderDaoImpl implements OrderDao {
    // 查询所有订单
    @Override
    public List<OrderBo> selectAllOrders() {
        return DBManager.commonQuery("SELECT user.u_id,orders.o_id,orders.o_count,orders.o_state,orders.o_time,user.u_name FROM orders,user WHERE orders.is_delete=1", OrderBo.class);
    }

    // 根据用户名或订单状态进行模糊搜索订单
    @Override
    public List<OrderBo> searchOrders(String userName, Integer orderState) {
        // 动态构建SQL查询
        StringBuilder sql = new StringBuilder(
                "SELECT user.u_id, orders.o_id, orders.o_count, orders.o_state, orders.o_time, user.u_name " +
                        "FROM orders INNER JOIN user ON orders.u_id = user.u_id WHERE 1=1"
        );

        List<Object> params = new ArrayList<>();

        // 如果 userName 不是空字符串，则添加用户名的模糊查询条件
        if (userName != null && !userName.isEmpty()) {
            sql.append(" AND user.u_name LIKE ?");
            params.add("%" + userName + "%");
        }

        // 如果 orderState 不是 null，则添加订单状态的查询条件
        if (orderState != null) {
            sql.append(" AND orders.o_state = ?");
            params.add(orderState);
        }

        return DBManager.commonQuery(sql.toString(), OrderBo.class, params.toArray());
    }


    // 修改订单状态
    @Override
    public boolean updateOrderStatus(int orderId, int status) {
        int result = DBManager.commonUpdate("UPDATE orders SET o_state = ? WHERE o_id = ?", status, orderId);
        return result > 0;
    }
}

